使用ajax报405错误 | 您所在的位置:网站首页 › 405 method not allowed options › 使用ajax报405错误 |
今天照葫芦画瓢学着使用ajax, 前端代码如下: 用户名: ;* 登录密码: ;* 重复输入密码: ;* 电子邮箱: ;* 手机号码: $(function () { var data ={ username:'$("#username").val()', password:'$("#password").val()', rePassword:'$("#rePassword").val()', email:'$("#email").val()', phone:'$("#phone").val()' }; $('#submit').click(function () { $.ajax({ type:"POST", url:"/register/function", data:data, dataType:"json", contentType: 'application/json', success:function (data) { } }) }) })
后台代码是以JSON格式接收的,代码如下: @PostMapping("/register/function") public String register(@Valid @RequestBody RegisterForm registerForm){ if(registerForm.getPassword().isEmpty()){ String massage="密码不能为空"; } return "redirect:/index"; } public class RegisterForm { private String username; private String password; private String rePassword; private String email; private String phone; ... }
然后一直报405错误,后台提示JSON转换失败,报错内容如下: Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'username': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'username': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false') at [Source: (PushbackInputStream); line: 1, column: 10]]后来请教了前端大佬,发现是ajax在传参数的时候没有转成String,原来传送的data传的是一个JSON对象 把data转成字符串就可以了
笔记: data:{"name":name,"sex":sex}, data的值是一个对象 data:"{\"name\":\""+name+"\",\"sex\":\""+sex+"\"}", data的值是一个字符串另外,使用ajax时,form标签中就不要写action了,提交按钮的type也不能用submit了(即不要用type=“submit”),要改成普通的button(即type=“button”)
另外,大佬不推荐使用$ajax,他推荐使用axios 于是,我上面的那种传参方式可以改写成: $(function () { var data ={ username:'$("#username").val()', password:'$("#password").val()', rePassword:'$("#rePassword").val()', email:'$("#email").val()', phone:'$("#phone").val()' }; $('#submit').click(function () { //get方法 axios.get("/register/function", data).then(function(res) { console.log('then', res); }).catch(function(res) { console.log('catch', res); }); //post方法,url不带参数aaa axios.post("/register/function", data, {}).then(function(res) { console.log('then', res); }).catch(function(res) { console.log('catch', res); }); //post方法,url后带参数aaa axios.post("/register/function", data, {params: { aaa:1, } }).then(function(res) { console.log('then', res); }).catch(function(res) { console.log('catch', res); }); }) })
|
CopyRight 2018-2019 实验室设备网 版权所有 |